package com.example.admin.testdemo.dao;

import android.content.Context;

import com.example.admin.testdemo.enty.Result;
import com.example.admin.testdemo.helper.DatabaseHelper;
import com.j256.ormlite.dao.Dao;

import java.sql.SQLException;
import java.util.List;

public class ResultDao {
    private Dao<Result, Integer> userDaoOpe;
    private DatabaseHelper helper;
    private static ResultDao instance;
    private String TAG = getClass().getName();

    private ResultDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            userDaoOpe = helper.getDao(Result.class);
        } catch (SQLException e) {
        }
    }

    public static synchronized ResultDao getResultDaoInstance(Context context) {
        if (instance == null) {
            synchronized (DatabaseHelper.class) {
                if (instance == null) {
                    instance = new ResultDao(context);
                }
            }
        }

        return instance;
    }


    public int add(Result breed) {
        try {
            if(isEixt(breed.getName())){
                userDaoOpe.update(breed);
            }else {
                userDaoOpe.create(breed);
            }
        } catch (SQLException e) {
            return -1;
        }
        return 0;
    }

    public boolean isEixt(String name) {
        try {
            List<Result> user = userDaoOpe.queryBuilder().where().eq("name", name).query();
            if (user != null && !user.isEmpty()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }


    public void deleteResult(Result advertisementBean) {
        try {
            if (advertisementBean != null) {
                userDaoOpe.delete(advertisementBean);
            }

        } catch (SQLException e) {
        }
    }

    public Result getResultByName(String name) {

        Result temp = null;
        try {
            List<Result> list = userDaoOpe.queryBuilder().where().eq("name", name).query();
            if (list != null && !list.isEmpty()) {
                temp = list.get(0);
            }
        } catch (SQLException e) {
        }
        return temp;
    }

    public void deleteResult(List<Result> list) {
        try {
            if (list != null && !list.isEmpty()) {
                userDaoOpe.delete(list);
            }

        } catch (SQLException e) {
        }
    }


}
